#include <stdio.h>
#include <pthread.h>


//全局变量
//在两个子线程中都要对gNumber进行修改，
//导致出现了bug
//
//此时全局变量成为了临界资源，必须要进行加锁
//不同的子线程要互斥访问临界资源
int gNumber = 0;
pthread_mutex_t mutex;

void * threadFunc1(void *)
{
    int cnt = 100000;
    while(cnt-- > 0) {
        pthread_mutex_lock(&mutex);
        ++gNumber;
        printf("sub thread 1 do add operation, gNumber:%d\n", gNumber);
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

void * threadFunc2(void *)
{
    int cnt = 100000;
    while(cnt-- > 0) {
        pthread_mutex_lock(&mutex);
        ++gNumber;
        printf("sub thread 2 do add operation, gNumber:%d\n", gNumber);
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}


int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_t pthid1, pthid2;
    pthread_create(&pthid1, NULL, threadFunc1, NULL);
    pthread_create(&pthid2, NULL, threadFunc2, NULL);

    pthread_join(pthid1, NULL);
    pthread_join(pthid2, NULL);

    printf("main thread: gNumber: %d\n", gNumber);

    pthread_mutex_destroy(&mutex);
    return 0;
}

